﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using PresentationLayerMVC.Models;
using DataAccessLayer.Models;
using System.Web.Routing;

namespace PresentationLayerMVC.Controllers
{
    public class LoginController : BaseController
    {
        IUserRepository repo;

        public LoginController()
        {
            repo = new UserRepository();
        }

        // GET: /Login/
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LogOnModel m)
        {
            string username = m.UserName;
            string password = m.Password;

            User user = repo.GetUser(username, password);

            if (user != null)
            {
                PutUserSession(user);
                return Next(Constants.ACT_LOGIN);
            }

            return View();
        }

        [HttpPost]
        public ActionResult Logout(LogOnModel m)
        {
            User user = repo.GetUser(GetUserIdFromSession());
            if (user != null)
            {
                user.LastLoginDate = DateTime.Now;
                UpdateModel(user);
                repo.Save();
            }

            RemoveUserSession();

            return Next(Constants.ACT_LOGOUT);
        }
    }
}
